package com.chinaums.study.restful.service;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class FileCacheService {

    private Map<String, byte[]> cache = new HashMap<>();
    private Map<String, Long> timestamp = new HashMap<>();

    public String put(final InputStream in) throws IOException {
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        IOUtils.copy(in, out);
        final byte[] bytes = out.toByteArray();
        final String md5 = DigestUtils.md5Hex(bytes);
        cache.put(md5, bytes);
        timestamp.put(md5, System.currentTimeMillis());
        return md5;
    }

    public byte[] load(final String md5) {
        return cache.get(md5);
    }

    @Scheduled(fixedDelay = 5000)
    private void clear() {
        timestamp.entrySet().stream()
                .filter(e -> System.currentTimeMillis() - e.getValue() > 60000)
                .map(Map.Entry::getKey)
                .collect(Collectors.toList())
                .forEach(k -> {
                    cache.remove(k);
                    timestamp.remove(k);
                });
    }
}
